import React, { useEffect } from 'react';
import styles from './homePage.less';
import GlobalHeader from '@/component/globalHeader';
import Recommend from '@/component/recommend';
import { Affix } from 'antd';
import { useScroll, useRequest } from '@umijs/hooks';
import { recommend } from '@/services/homePageService';
import { recommendList } from '@/common/homePage';

interface recommendListResult {
  list: recommendList[];
}

const HomePage: React.FC<any> = () => {
  const [scroll] = useScroll(document);
  const { data, loading, loadMore, loadingMore } = useRequest(
    (d: recommendListResult) => recommend(),
    {
      loadMore: true,
      cacheKey: 'recommendList',
      formatResult: res => {
        return {
          list: [res],
        };
      },
    },
  );

  useEffect(() => {
    let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
    let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
    if (
      scrollHeight > clientHeight &&
      scroll.top + clientHeight > scrollHeight - 20 &&
      !loadingMore
    ) {
      loadMore();
    }
  }, [loadMore, loadingMore, scroll]);

  function recommendList(data: recommendListResult) {
    return (
      data &&
      data.list.map(item => {
        return item.data.map((value, index) => {
          return <Recommend data={value} key={index}></Recommend>;
        });
      })
    );
  }

  return (
    <React.Fragment>
      <div style={{ padding: '52px 0 0 0' }}>
        <Affix style={{ position: 'absolute', top: 0, left: 0, width: '100%' }}>
          <GlobalHeader></GlobalHeader>
        </Affix>
      </div>
      <div className={styles.Topstory}>
        <div className={styles['Topstory-container']}>
          <div className={styles['Topstory-mainColumn']}>
            <a href="https://www.zhihu.com/special/19681091">
              <img
                src={require('../../images/v2-6e8fccc8a30e8cf15a90e7a894011579_r.jpg')}
                alt=""
                className={styles['css-vnkjjr']}
              />
            </a>
            <div className={styles['Topstory-mainColumnCard']}>
              <div className={styles['Topstory-tabCard']}></div>
              <div className={styles['TopstoryContent']}>
                <div className={styles['ListShortcut']}>{data && recommendList(data)}</div>
                {loadingMore && <div style={{ fontSize: 50, fontWeight: 600 }}>loading.......</div>}
              </div>
            </div>
          </div>
          <div className={styles['GlobalSideBar']}></div>
        </div>
      </div>
    </React.Fragment>
  );
};

export default HomePage;
